<template>
	<view class="content">
		<u-swiper :list="swiperList" indicator indicatorMode="line" circular height="320rpx"></u-swiper>
		<u-tabs :list="tabList" @click="tabClick"></u-tabs>
		<goods-item :goods="goods"></goods-item>
		<u-loading-icon :show="isLoading" text="加载中" ></u-loading-icon>
		<view class="isend" v-show="isEnd">----我也是有底线的----</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabList: [
					{
						name: '默认',
					},
					{
						name: '热销',
					},
					{
						name: '推荐'
					},
					{
						name: '最新'
					}
				],
				slides: [],
				goods: [],
				currentPage: 1,
				sales: 0,
				recommend: 0,
				new: 0,
				isLoading: false,
				// 判断数据是否请求到最后一页
				isEnd: false	
			}
		},
		async onLoad() {
			// const userInfo = await uni.$u.http.get('/api/user')
			
			this.getIndexData()
		},
		onReachBottom() {
			if (!this.isEnd) {
				this.currentPage++
				this.getIndexData()
			}
		},
		computed: {
			swiperList() {
				const arr = this.slides.map(item => {
					return item.img_url
				})
				return arr
			}
		},
		methods: {
			async getIndexData(callback) {
				this.isLoading = true
				const res = await uni.$u.http.get('/api/index', {
					params: {
						page: this.currentPage,
						sales: this.sales,
						recommend: this.recommend,
						new: this.new
					}
				})
				callback && callback() 
				this.slides = res.slides
				let temp = res.goods.data
				if (temp.length < 10) {
					this.isEnd = true
				}
				this.goods.push(...temp)
				// console.log(res.goods)
				this.isLoading = false
			},
			tabClick(e) {
				this.goods = []
				this.isEnd = false
				this.sales = 0
				this.recommend = 0
				this.new = 0
				if (e.index === 1) {
					this.sales = 1
				} else if (e.index === 2) {
					this.recommend = 1
				} else if (e.index === 3) {
					this.new = 1
				}
				// 解决快速切换tab栏时出现的goods中会将之前选项卡中的数据也保存下来的bug
				this.getIndexData(() => {
					this.goods = []
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.isend {
		margin: 20rpx 0;
		text-align: center;
	}
</style>
